package com.becca.cake.core.freemarker;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * freemarket模板工具类
 * @copyright  尊星(上海)信息科技有限公司
 * @author hejinguo
 * @date 2016年6月15日 下午1:13:41
 */
public class FreeMarkerHelp {
    private static Logger        logger = Logger.getLogger(FreeMarkerHelp.class);
    private static String        fomart = "UTF-8";
    private static Configuration configuration;

    public void setFreemarkerConfiguration(Configuration configuration) {
        FreeMarkerHelp.configuration = configuration;
    }

    /**
     * 在指定的模板中填充数据后返回模板内容
     * @author hejingou
     * @param map
     * @param ftlName
     * @return
     * @throws TemplateException 
     * @throws IOException 
     * @throws Exception 
     */
    public static String getTemplateHtml(Map<String, Object> map, String ftlName) throws Exception {
        String resultTemplateHtml = "";
        //获取指定的模板
        Template getTemplate = configuration.getTemplate(ftlName, fomart);
        getTemplate.setEncoding(fomart);
        resultTemplateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(getTemplate, map);
        logger.info("xml文件信息:" + resultTemplateHtml);
        return resultTemplateHtml;
    }

    /**
     * 创建静态文件
     * @param ftlName
     * @param htmlPath  通过方法  getFreeMarketFoderPath() 获取
     * @param map
     */
    public static boolean makeHtml(String ftlName, String htmlPath, Map<String, Object> map) {
        configuration.setEncoding(Locale.CHINA, fomart);
        boolean result = false;
        try {
            Template getTemplate = configuration.getTemplate(ftlName, fomart);
            Writer out = new OutputStreamWriter(new FileOutputStream(htmlPath));
            getTemplate.process(map, out);
            out.flush();
            out.close();
            result = true;
        } catch (IOException e) {
            if (logger.isInfoEnabled()) {
                logger.error("加载FTL模板路径错误!", e);
            }
        } catch (TemplateException e) {
            if (logger.isInfoEnabled()) {
                logger.error("FTL模板中加载数据异常!", e);
            }
        } catch (Exception e) {
            logger.error("加载配置文件错误!", e);
        }
        return result;
    }
}
